﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ordinaire.Db;
using Ordinaire.Taxonomy.Data;

namespace Ordinaire.Taxonomy
{
    /// <summary>
    /// Contains list of vocabularies exist in the data source.
    /// </summary>
    public class Vocabularies : BusinessManager<VocabDataManager, OContext>
    {
        #region Constructor

        /// <summary>
        /// Returns new instance of Ordinaire.Taxonomy.Vocabularies.
        /// </summary>
        public Vocabularies()
        {
            base.dataManager = new VocabDataManager();
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Returns instance of Ordinaire.Taxonomy.Vocab with the specified name.
        /// </summary>
        /// <param name="name">the vocabulary</param>
        /// <returns>instance of Ordinaire.Taxonomy.Vocab</returns>
        public Vocab Create(string name)
        {
            return Create<Vocabs>(name);
        }

        /// <summary>
        /// Returns instance of Ordinaire.Taxonomy.Vocab with the specified name from the specified table in the data source.
        /// </summary>
        /// <typeparam name="TVocab">the data table in the data source</typeparam>
        /// <param name="name">the vocabulary</param>
        /// <returns>instance of Ordinaire.Taxonomy.Vocab</returns>
        public Vocab Create<TVocab>(string name)
            where TVocab : Vocabs
        {
            name.ThrowIfNullOrEmpty<ArgumentException>("name");

            TVocab data = dataManager.GetByName<TVocab>(name);
            if (data == null)
            {
                data = dataManager.Insert<TVocab>(name);
            }

            return data.ToVocab();
        }

        #endregion
    }

    /// <summary>
    /// Contains list of extension methods related to Vocabularies.
    /// </summary>
    public static class VocabulariesExtension
    {
        /// <summary>
        /// Retrieves or creates the vocab id of the specified keyword.
        /// </summary>
        /// <typeparam name="TVocab">data table to use in the data source</typeparam>
        /// <param name="keyword">keyword used to create</param>
        /// <returns>the corresponding or generated data id of corresponding keyword</returns>
        public static int ToVocabId<TVocab>(this string keyword)
            where TVocab : Vocabs
        {
            if (String.IsNullOrEmpty(keyword))
            {
                return 0;
            }

            Vocab vocab = new Vocabularies().Create<TVocab>(keyword);
            if (vocab == null)
            {
                return 0;
            }
            return vocab.Id;
        }
    }
}
